import { User } from "../model/User.js";
import { Op } from "sequelize";

//查全部
async function userList(ctx) {
  let keyWord = ctx.request.query.keyWord || "";
  console.log(keyWord);
  let users;
  if (keyWord) {
    users = await User.findAll({
      where: {
        [Op.or]: [
          {
            uName: {
              [Op.like]: `%${keyWord}%`,
            },
          },
          {
            uAge: {
              [Op.like]: `%${keyWord}%`,
            },
          },
        ],
      },
    });
  } else {
    users = await User.findAll();
  }
  ctx.render("userList.html", {
    users,
    keyWord,
  });
}

//根据id查
async function userById(ctx) {
  let id = ctx.params.id;
  let user = await User.findByPk(id);
  // console.log(user.dataValues);
  ctx.render("updateUser.html", user.dataValues);
}

//根据id删除
async function delUserById(ctx) {
  let id = ctx.params.id;
  await User.destroy({
    where: {
      uId: id,
    },
  });
  console.log("根据id删除 id:", id);
  ctx.body = "删除成功";
}

//新增页面
async function addUserView(ctx) {
  console.log("新增用户页面");
  ctx.render("addUser.html", {});
}

//新增
async function addUser(ctx) {
  let obj = ctx.request.body;
  console.log("新增用户", obj);
  await User.create(obj);
  ctx.body = "新增成功";
}

//修改
async function updateUser(ctx) {
  let id = ctx.params.id;
  let user = User.findByPk(id);
  !user ? (ctx.request.body = "博客不存在无法进行修改") : "";
  let obj = ctx.request.body;
  await User.update(obj, {
    where: {
      uId: id,
    },
  });
  ctx.body = "修改成功";
}

//暴露路由对象便于拆解注册路由
export const users = {
  "get /users": userList,
  "get /user/:id": userById,
  "get /user": addUserView,
  "delete /user/:id": delUserById,
  "post /user": addUser,
  "put /user/:id": updateUser,
};
